package com.zkingsoft.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;




import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.zkingsoft.common.constance.AppConstance;

public class WxacodeUtil {
	/**
	 * 小程序秘钥
	 */
	private static final String XCX_SECRET = "xcx_secret";
	/**
	 * 小程序appid
	 */
	private static final String XCX_APPID = "xcx_appid";
	/**
	 * token获取地址
	 */
	private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
	
	/**
	 * token获取地址
	 */
	private static final String GET_WXACODE ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
	
    public static String getWxacode(String scene,String page,String fileName) throws Exception {
        //获取token
    	String appid = PropertiesUtil.getString(XCX_APPID);
		String secret = PropertiesUtil.getString(XCX_SECRET);
		 String result1 = get(TOKEN_URL.replace("APPID", appid).replace("SECRET", secret));
	     String access_token = JSONObject.parseObject(result1).getString("access_token");
        if(StringUtils.isNotBlank(access_token)) {
            Map<String, Object> params = new HashMap<>();
            params.put("scene", scene);
            params.put("page", page);
            params.put("width", 430);
            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(GET_WXACODE+access_token);
            String body = JSON.toJSONString(params);
            StringEntity entity;
            entity = new StringEntity(body);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();

    		// 图片保存目录路径
    		String baseSavePath = PropertiesUtil.getString(AppConstance.FILES_TORAGE_PATH);
    		// 图片保存目录URL
    		String baseSaveUrl = PropertiesUtil.getString(AppConstance.NGINX_URL);
            File targetFile = new File(baseSavePath);  
            if(!targetFile.exists()){    
                targetFile.mkdirs();    
            }       
        	// 创建图片文件夹
            baseSavePath += "wxacode" + File.separatorChar;
            baseSaveUrl += "wxacode"  + "/";
    		File saveDirFile = new File(baseSavePath);
    		if (!saveDirFile.exists()) {
    			saveDirFile.mkdirs();
    		}
    		baseSaveUrl += fileName+".png";
            FileOutputStream out = new FileOutputStream(baseSavePath+fileName+".png");
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
            return baseSaveUrl;
        } else {
        	 return null;
        }
    }

    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String get(String url) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(url, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return responseEntity.getBody();
    }
}
